//
//  MBRelatingPhoneController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/10/14.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBRelatingPhoneController.h"
#import "MBLoginController.h"
#import "MBTabBarController.h"

@interface MBRelatingPhoneController () {
    int             timeout;
    NSString        *codeStr;
    NSString        *iphoneStr;
}

@property (strong, nonatomic) IBOutlet UIView *phoneView;
@property (strong, nonatomic) IBOutlet UIView *codeView;
@property (strong, nonatomic) IBOutlet UIButton *bindingView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *phoneViewLeft;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *codeViewLeft;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *blidingViewLeft;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *phoneViewRight;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *codeViewRight;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *bindingViewTop;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *codeViewTop;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *phoneViewTop;

@property (weak, nonatomic) IBOutlet UIButton *SMSButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@end

@implementation MBRelatingPhoneController

- (void)back
{
    if (_formBaseViewCtrl) {
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([_formBaseViewCtrl isEqualToString:NSStringFromClass([controller class])]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    } else {
        MBTabBarController *tabBar = [[MBTabBarController alloc] init];
        [self presentViewController:tabBar animated:YES completion:nil];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    iphoneStr = @"";
    [self setBackItem];
    
    [self setupUI];
}


- (void )setupUI {
    
    
    [self setTitleView:@"绑定手机号"];
    self.view.backgroundColor = [UIColor whiteColor];
    self.phoneView.layer.cornerRadius = 5.0;
    self.phoneView.clipsToBounds = YES;
    self.codeView.layer.cornerRadius = 5.0;
    self.codeView.clipsToBounds = YES;
    self.bindingView.layer.cornerRadius = 5.0;
    self.bindingView.clipsToBounds = YES;
    
    UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
    bt.frame = CGRectMake(0, 0, 60, 30);
    [bt setTitle:@"跳过" forState: UIControlStateNormal];
    [bt setTitle:@"跳过" forState: UIControlStateHighlighted];
    bt.titleLabel.font = [UIFont systemFontOfSize:13];
    [bt setTitleEdgeInsets:UIEdgeInsetsMake(-40, 0, -40, -40)];
    [bt addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self setRightBarItems:bt];
    
    if (ISIPAD) {
        
        bt.titleLabel.font = [UIFont systemFontOfSize:14];

        _phoneViewLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _codeViewLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _phoneViewRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _codeViewRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _blidingViewLeft.constant = (SCREEN_WIDTH-700*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.))/2.;
        
        _phoneViewTop.constant = 140*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _codeViewTop.constant = 30*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _bindingViewTop.constant = 370*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        
    }

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [self.view addGestureRecognizer:tap];
}


- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    if (ISIPAD) {
        
        
        _phoneViewLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _codeViewLeft.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _phoneViewRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _codeViewRight.constant = 600*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _blidingViewLeft.constant = (SCREEN_WIDTH-700*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.))/2.;
        
        _phoneViewTop.constant = 140*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _codeViewTop.constant = 30*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
        _bindingViewTop.constant = 370*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.);
    }
}
//绑定
- (IBAction)bindingBtn:(id)sender {
    if (![self validateInputIsGetSMSCode:NO]) {
        return;
    }
    
    if (![codeStr isEqualToString:_codeField.text]) {
        [ErrorMessage showErrorMessage:@"验证码错误，请重试!" inView:self.view];
        return;
    }
    
    if (![iphoneStr isEqualToString:_phoneField.text]) {
        [ErrorMessage showErrorMessage:@"手机号码不一致,请重试!" inView:self.view];
        return;
    }
    
    UserModel *model = [UserManager standerDefult].userModel;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:VERIFICATION_BINDPHONE_URL_PATH,model.UserID,_phoneField.text] view:nil success:^(id json) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] intValue] == 0) {
                [self back];
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}
//跳过
- (void)onSelectedSkip {
    
    MBLoginController *loginVC = [[MBLoginController alloc] init];
    loginVC.formBaseViewCtrl = NSStringFromClass([self class]);
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)hideKeyBoard
{
    [self.view endEditing:YES];
}

- (IBAction)onGetCode:(id)sender {
    if (![self validateInputIsGetSMSCode:YES]) {
        return;
    }
    NSString *url = [NSString stringWithFormat:VERIFICATION_PWD_URL_PATH,_phoneField.text,@"SMS_22385059"];
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        if ([str hasPrefix:@"InvalidSendSmsFrequency limit reaches"]) {
            //失败
            [ErrorMessage showErrorMessage:@"获取失败" inView:self.view];
        } else {
            //成功
            codeStr =  [str substringWithRange:NSMakeRange(str.length-7, 6)];
            iphoneStr = _phoneField.text;
            [ErrorMessage showErrorMessage:@"短信已下发" inView:self.view];
            [self startTime];
        }
        
    }];
}

-(void)startTime{
    timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_SMSButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                _SMSButton.userInteractionEnabled = YES;
                codeStr = @"";
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_SMSButton setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                _SMSButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (BOOL)validateInputIsGetSMSCode:(BOOL)getSMSCode{
    if ([_phoneField.text isEqual:@""]) {
        NSLog(@"请输入手机号");
        [ErrorMessage showErrorMessage:@"请输入手机号" inView:self.view];
        return NO;
    }else{
        if (![_phoneField.text isVAlidPhoneNumber]) {
            NSLog(@"手机号不合法");
            [ErrorMessage showErrorMessage:@"手机号不合法" inView:self.view];
            return NO;
        }
    }
    
    if (getSMSCode) {//获取验证码只需check手机号
        return YES;
    }
    
    if ([_codeField.text isEqual:@""]) {
        NSLog(@"请输入验证码");
        [ErrorMessage showErrorMessage:@"请输入验证码" inView:self.view];
        
        return NO;
    }
    return YES;
}

@end
